import { ref, computed } from 'vue'
import { useStorage } from './useStorage'
interface TodoItem {
    title?: string,
    done?: boolean
}

export const useTodos = () => {
    const todoName = ref<string>('')
    const showInfo = ref<boolean>(false)
    const showInfoTimer = ref<any>(null)
    // const todoList = ref<TodoItem[]>()
    const initTodo: TodoItem[] = [
        {
            title: '学习',
            done: false,
        }
    ]
    const { data: todoList } = useStorage('todos', initTodo)
    const add = () => {
        if (!todoName.value) {
            showInfo.value = true
            clearTimeout(showInfoTimer.value)
            showInfoTimer.value = setTimeout(() => {
                showInfo.value = false
            }, 2000)
            return
        }
        todoList.value.push({
            title: todoName.value,
            done: false
        })
        todoName.value = ''
    }
    const clearTodo = () => {
        todoList.value = todoList.value.filter(item => !item.done)
    }

    const activeLen = computed(() => todoList.value.filter(item => !item.done).length)
    const allDone = computed({
        get() {
            return activeLen.value === 0
        },
        set(val) {
            todoList.value.forEach(item => {
                item.done = val
            })
        }
    })
    return {
        todoName,
        showInfo,
        todoList,
        add,
        clearTodo,
        activeLen,
        allDone
    }
}